"""
课堂质量评估AI系统服务
实现学生专注度检测、参与度分析和学习效果预测
"""
import asyncio
import logging
import numpy as np
from datetime import datetime, timedelta
from typing import List, Dict, Optional, Tuple, Any
from uuid import uuid4
import time
from collections import defaultdict, deque
import json
from enum import Enum
import cv2

logger = logging.getLogger(__name__)


class AttentionLevel(str, Enum):
    """专注度等级枚举"""
    VERY_HIGH = "very_high"      # 非常专注
    HIGH = "high"                # 高度专注
    MEDIUM = "medium"            # 中等专注
    LOW = "low"                  # 低专注
    VERY_LOW = "very_low"        # 非常不专注


class ParticipationLevel(str, Enum):
    """参与度等级枚举"""
    VERY_ACTIVE = "very_active"  # 非常活跃
    ACTIVE = "active"            # 活跃
    MODERATE = "moderate"        # 中等
    PASSIVE = "passive"          # 被动
    INACTIVE = "inactive"        # 不活跃


class LearningBehavior(str, Enum):
    """学习行为类型枚举"""
    LISTENING = "listening"          # 听讲
    TAKING_NOTES = "taking_notes"    # 记笔记
    RAISING_HAND = "raising_hand"    # 举手
    DISCUSSING = "discussing"        # 讨论
    READING = "reading"              # 阅读
    DISTRACTED = "distracted"        # 分心
    SLEEPING = "sleeping"            # 睡觉
    USING_PHONE = "using_phone"      # 使用手机


class ClassroomAtmosphere(str, Enum):
    """课堂氛围枚举"""
    EXCELLENT = "excellent"      # 优秀
    GOOD = "good"               # 良好
    AVERAGE = "average"         # 一般
    POOR = "poor"               # 较差
    VERY_POOR = "very_poor"     # 很差


class StudentAttentionData:
    """学生专注度数据"""
    def __init__(self, student_id: str, timestamp: datetime, attention_level: AttentionLevel,
                 attention_score: float, face_direction: Dict[str, float], 
                 eye_gaze: Dict[str, float], posture: Dict[str, Any],
                 behavior: LearningBehavior, confidence: float):
        self.student_id = student_id
        self.timestamp = timestamp
        self.attention_level = attention_level
        self.attention_score = attention_score  # 0-100
        self.face_direction = face_direction    # 面部朝向
        self.eye_gaze = eye_gaze               # 眼神注视
        self.posture = posture                 # 姿态信息
        self.behavior = behavior               # 当前行为
        self.confidence = confidence           # 检测置信度


class StudentParticipationData:
    """学生参与度数据"""
    def __init__(self, student_id: str, timestamp: datetime, participation_level: ParticipationLevel,
                 participation_score: float, interaction_count: int, 
                 hand_raising_count: int, speaking_duration: float,
                 question_asking_count: int, answer_giving_count: int):
        self.student_id = student_id
        self.timestamp = timestamp
        self.participation_level = participation_level
        self.participation_score = participation_score  # 0-100
        self.interaction_count = interaction_count
        self.hand_raising_count = hand_raising_count
        self.speaking_duration = speaking_duration      # 发言时长（秒）
        self.question_asking_count = question_asking_count
        self.answer_giving_count = answer_giving_count


class ClassroomAnalysisResult:
    """课堂分析结果"""
    def __init__(self, analysis_id: str, classroom_id: str, session_id: str,
                 analysis_period: Tuple[datetime, datetime], student_count: int,
                 average_attention_score: float, average_participation_score: float,
                 attention_distribution: Dict[str, int], participation_distribution: Dict[str, int],
                 behavior_statistics: Dict[str, int], classroom_atmosphere: ClassroomAtmosphere,
                 engagement_trends: Dict[str, Any], learning_effectiveness: float,
                 recommendations: List[str]):
        self.analysis_id = analysis_id
        self.classroom_id = classroom_id
        self.session_id = session_id
        self.analysis_period = analysis_period
        self.student_count = student_count
        self.average_attention_score = average_attention_score
        self.average_participation_score = average_participation_score
        self.attention_distribution = attention_distribution
        self.participation_distribution = participation_distribution
        self.behavior_statistics = behavior_statistics
        self.classroom_atmosphere = classroom_atmosphere
        self.engagement_trends = engagement_trends
        self.learning_effectiveness = learning_effectiveness
        self.recommendations = recommendations


class LearningPrediction:
    """学习效果预测"""
    def __init__(self, student_id: str, prediction_id: str, predicted_performance: float,
                 risk_level: str, learning_style: str, strengths: List[str],
                 weaknesses: List[str], recommendations: List[str], confidence: float):
        self.student_id = student_id
        self.prediction_id = prediction_id
        self.predicted_performance = predicted_performance  # 0-100
        self.risk_level = risk_level                       # low, medium, high
        self.learning_style = learning_style               # visual, auditory, kinesthetic
        self.strengths = strengths
        self.weaknesses = weaknesses
        self.recommendations = recommendations
        self.confidence = confidence


class AttentionDetector:
    """专注度检测器"""
    
    def __init__(self):
        self.face_cascade = None  # 人脸检测器
        self.eye_cascade = None   # 眼部检测器
        self.pose_detector = None # 姿态检测器
        
        # 专注度评估参数
        self.attention_weights = {
            'face_direction': 0.3,    # 面部朝向权重
            'eye_gaze': 0.3,         # 眼神注视权重
            'posture': 0.2,          # 姿态权重
            'behavior': 0.2          # 行为权重
        }
    
    async def detect_student_attention(self, image: np.ndarray, student_bbox: Tuple[int, int, int, int],
                                     student_id: str) -> StudentAttentionData:
        """检测学生专注度"""
        timestamp = datetime.now()
        
        # 提取学生区域
        x, y, w, h = student_bbox
        student_roi = image[y:y+h, x:x+w]
        
        # 分析面部朝向
        face_direction = await self._analyze_face_direction(student_roi)
        
        # 分析眼神注视
        eye_gaze = await self._analyze_eye_gaze(student_roi)
        
        # 分析姿态
        posture = await self._analyze_posture(student_roi)
        
        # 识别行为
        behavior = await self._recognize_behavior(student_roi, posture)
        
        # 计算专注度分数
        attention_score = self._calculate_attention_score(
            face_direction, eye_gaze, posture, behavior
        )
        
        # 确定专注度等级
        attention_level = self._determine_attention_level(attention_score)
        
        # 计算置信度
        confidence = self._calculate_confidence(face_direction, eye_gaze, posture)
        
        return StudentAttentionData(
            student_id=student_id,
            timestamp=timestamp,
            attention_level=attention_level,
            attention_score=attention_score,
            face_direction=face_direction,
            eye_gaze=eye_gaze,
            posture=posture,
            behavior=behavior,
            confidence=confidence
        )
    
    async def _analyze_face_direction(self, roi: np.ndarray) -> Dict[str, float]:
        """分析面部朝向"""
        # 模拟面部朝向分析
        # 实际实现中会使用人脸关键点检测
        
        # 模拟朝向角度（相对于摄像头）
        yaw = np.random.uniform(-30, 30)      # 左右转头角度
        pitch = np.random.uniform(-20, 20)    # 上下点头角度
        roll = np.random.uniform(-15, 15)     # 左右倾斜角度
        
        # 计算朝向分数（面向前方得分最高）
        forward_score = max(0, 100 - abs(yaw) * 2 - abs(pitch) * 1.5)
        
        return {
            'yaw': yaw,
            'pitch': pitch,
            'roll': roll,
            'forward_score': forward_score,
            'is_facing_forward': abs(yaw) < 15 and abs(pitch) < 10
        }
    
    async def _analyze_eye_gaze(self, roi: np.ndarray) -> Dict[str, float]:
        """分析眼神注视"""
        # 模拟眼神注视分析
        # 实际实现中会使用眼球追踪技术
        
        # 模拟注视方向
        gaze_x = np.random.uniform(-1, 1)  # 水平注视方向
        gaze_y = np.random.uniform(-1, 1)  # 垂直注视方向
        
        # 计算注视分数（注视前方得分最高）
        gaze_score = max(0, 100 - abs(gaze_x) * 50 - abs(gaze_y) * 30)
        
        # 模拟眨眼频率（正常范围15-20次/分钟）
        blink_rate = np.random.uniform(12, 25)
        
        return {
            'gaze_x': gaze_x,
            'gaze_y': gaze_y,
            'gaze_score': gaze_score,
            'blink_rate': blink_rate,
            'is_looking_forward': abs(gaze_x) < 0.3 and abs(gaze_y) < 0.3
        }
    
    async def _analyze_posture(self, roi: np.ndarray) -> Dict[str, Any]:
        """分析姿态"""
        # 模拟姿态分析
        # 实际实现中会使用姿态估计模型
        
        # 模拟身体姿态参数
        spine_angle = np.random.uniform(-20, 20)      # 脊柱角度
        shoulder_level = np.random.uniform(-10, 10)   # 肩膀水平度
        head_tilt = np.random.uniform(-15, 15)        # 头部倾斜
        
        # 计算姿态分数（端正坐姿得分最高）
        posture_score = max(0, 100 - abs(spine_angle) * 2 - abs(shoulder_level) * 3 - abs(head_tilt) * 2)
        
        # 判断姿态类型
        if posture_score > 80:
            posture_type = "upright"      # 端正
        elif posture_score > 60:
            posture_type = "slightly_slouched"  # 轻微弯腰
        elif posture_score > 40:
            posture_type = "slouched"     # 弯腰
        else:
            posture_type = "poor"         # 姿态不良
        
        return {
            'spine_angle': spine_angle,
            'shoulder_level': shoulder_level,
            'head_tilt': head_tilt,
            'posture_score': posture_score,
            'posture_type': posture_type,
            'is_upright': posture_score > 70
        }
    
    async def _recognize_behavior(self, roi: np.ndarray, posture: Dict[str, Any]) -> LearningBehavior:
        """识别学习行为"""
        # 模拟行为识别
        # 实际实现中会使用行为识别模型
        
        behaviors = [
            LearningBehavior.LISTENING,
            LearningBehavior.TAKING_NOTES,
            LearningBehavior.READING,
            LearningBehavior.DISTRACTED,
            LearningBehavior.SLEEPING
        ]
        
        # 根据姿态调整行为概率
        if posture['posture_score'] < 30:
            # 姿态不良时更可能是睡觉或分心
            weights = [0.1, 0.1, 0.1, 0.4, 0.3]
        elif posture['posture_score'] > 80:
            # 姿态良好时更可能是听讲或记笔记
            weights = [0.4, 0.3, 0.2, 0.08, 0.02]
        else:
            # 中等姿态时各种行为都有可能
            weights = [0.3, 0.2, 0.2, 0.2, 0.1]
        
        return np.random.choice(behaviors, p=weights)
    
    def _calculate_attention_score(self, face_direction: Dict[str, float], 
                                 eye_gaze: Dict[str, float], posture: Dict[str, Any],
                                 behavior: LearningBehavior) -> float:
        """计算专注度分数"""
        # 基础分数计算
        face_score = face_direction['forward_score']
        gaze_score = eye_gaze['gaze_score']
        posture_score = posture['posture_score']
        
        # 行为分数
        behavior_scores = {
            LearningBehavior.LISTENING: 90,
            LearningBehavior.TAKING_NOTES: 95,
            LearningBehavior.READING: 85,
            LearningBehavior.RAISING_HAND: 100,
            LearningBehavior.DISCUSSING: 80,
            LearningBehavior.DISTRACTED: 30,
            LearningBehavior.SLEEPING: 10,
            LearningBehavior.USING_PHONE: 20
        }
        behavior_score = behavior_scores.get(behavior, 50)
        
        # 加权计算总分
        total_score = (
            face_score * self.attention_weights['face_direction'] +
            gaze_score * self.attention_weights['eye_gaze'] +
            posture_score * self.attention_weights['posture'] +
            behavior_score * self.attention_weights['behavior']
        )
        
        return max(0, min(100, total_score))
    
    def _determine_attention_level(self, attention_score: float) -> AttentionLevel:
        """确定专注度等级"""
        if attention_score >= 85:
            return AttentionLevel.VERY_HIGH
        elif attention_score >= 70:
            return AttentionLevel.HIGH
        elif attention_score >= 55:
            return AttentionLevel.MEDIUM
        elif attention_score >= 40:
            return AttentionLevel.LOW
        else:
            return AttentionLevel.VERY_LOW
    
    def _calculate_confidence(self, face_direction: Dict[str, float], 
                            eye_gaze: Dict[str, float], posture: Dict[str, Any]) -> float:
        """计算检测置信度"""
        # 基于检测质量计算置信度
        face_quality = 1.0 if face_direction['is_facing_forward'] else 0.7
        gaze_quality = 1.0 if eye_gaze['is_looking_forward'] else 0.8
        posture_quality = posture['posture_score'] / 100.0
        
        confidence = (face_quality + gaze_quality + posture_quality) / 3.0
        return min(1.0, max(0.0, confidence))


class ParticipationAnalyzer:
    """参与度分析器"""
    
    def __init__(self):
        self.interaction_tracker = defaultdict(list)
        self.speaking_tracker = defaultdict(float)
        self.hand_raising_tracker = defaultdict(int)
    
    async def analyze_student_participation(self, student_id: str, 
                                          attention_data: StudentAttentionData,
                                          audio_features: Optional[Dict[str, Any]] = None) -> StudentParticipationData:
        """分析学生参与度"""
        timestamp = datetime.now()
        
        # 更新交互记录
        self._update_interaction_tracking(student_id, attention_data, audio_features)
        
        # 计算参与度指标
        interaction_count = len(self.interaction_tracker[student_id])
        hand_raising_count = self.hand_raising_tracker[student_id]
        speaking_duration = self.speaking_tracker[student_id]
        
        # 模拟问答统计
        question_asking_count = np.random.poisson(0.5)  # 平均每节课0.5个问题
        answer_giving_count = np.random.poisson(1.0)    # 平均每节课1个回答
        
        # 计算参与度分数
        participation_score = self._calculate_participation_score(
            interaction_count, hand_raising_count, speaking_duration,
            question_asking_count, answer_giving_count, attention_data.attention_score
        )
        
        # 确定参与度等级
        participation_level = self._determine_participation_level(participation_score)
        
        return StudentParticipationData(
            student_id=student_id,
            timestamp=timestamp,
            participation_level=participation_level,
            participation_score=participation_score,
            interaction_count=interaction_count,
            hand_raising_count=hand_raising_count,
            speaking_duration=speaking_duration,
            question_asking_count=question_asking_count,
            answer_giving_count=answer_giving_count
        )
    
    def _update_interaction_tracking(self, student_id: str, 
                                   attention_data: StudentAttentionData,
                                   audio_features: Optional[Dict[str, Any]]):
        """更新交互跟踪"""
        # 记录举手行为
        if attention_data.behavior == LearningBehavior.RAISING_HAND:
            self.hand_raising_tracker[student_id] += 1
            self.interaction_tracker[student_id].append({
                'type': 'hand_raising',
                'timestamp': attention_data.timestamp,
                'confidence': attention_data.confidence
            })
        
        # 记录讨论行为
        if attention_data.behavior == LearningBehavior.DISCUSSING:
            self.interaction_tracker[student_id].append({
                'type': 'discussing',
                'timestamp': attention_data.timestamp,
                'confidence': attention_data.confidence
            })
        
        # 记录发言时长（基于音频特征）
        if audio_features and audio_features.get('is_speaking', False):
            self.speaking_tracker[student_id] += audio_features.get('duration', 1.0)
    
    def _calculate_participation_score(self, interaction_count: int, hand_raising_count: int,
                                     speaking_duration: float, question_asking_count: int,
                                     answer_giving_count: int, attention_score: float) -> float:
        """计算参与度分数"""
        # 基础参与度分数
        base_score = attention_score * 0.4  # 专注度占40%
        
        # 交互行为分数
        interaction_score = min(30, interaction_count * 5)  # 交互次数，最高30分
        hand_raising_score = min(15, hand_raising_count * 3)  # 举手次数，最高15分
        speaking_score = min(10, speaking_duration * 2)  # 发言时长，最高10分
        qa_score = min(5, (question_asking_count + answer_giving_count) * 2.5)  # 问答，最高5分
        
        total_score = base_score + interaction_score + hand_raising_score + speaking_score + qa_score
        
        return max(0, min(100, total_score))
    
    def _determine_participation_level(self, participation_score: float) -> ParticipationLevel:
        """确定参与度等级"""
        if participation_score >= 85:
            return ParticipationLevel.VERY_ACTIVE
        elif participation_score >= 70:
            return ParticipationLevel.ACTIVE
        elif participation_score >= 55:
            return ParticipationLevel.MODERATE
        elif participation_score >= 40:
            return ParticipationLevel.PASSIVE
        else:
            return ParticipationLevel.INACTIVE


class ClassroomAnalyzer:
    """课堂分析器"""
    
    def __init__(self):
        self.attention_history = defaultdict(list)
        self.participation_history = defaultdict(list)
    
    def analyze_classroom_session(self, classroom_id: str, session_id: str,
                                attention_data_list: List[StudentAttentionData],
                                participation_data_list: List[StudentParticipationData]) -> ClassroomAnalysisResult:
        """分析课堂会话"""
        analysis_id = str(uuid4())
        
        if not attention_data_list:
            raise ValueError("No attention data provided")
        
        # 确定分析周期
        timestamps = [data.timestamp for data in attention_data_list]
        analysis_period = (min(timestamps), max(timestamps))
        
        # 统计学生数量
        student_ids = set(data.student_id for data in attention_data_list)
        student_count = len(student_ids)
        
        # 计算平均分数
        average_attention_score = np.mean([data.attention_score for data in attention_data_list])
        average_participation_score = np.mean([data.participation_score for data in participation_data_list]) if participation_data_list else 0
        
        # 分析专注度分布
        attention_distribution = self._analyze_attention_distribution(attention_data_list)
        
        # 分析参与度分布
        participation_distribution = self._analyze_participation_distribution(participation_data_list)
        
        # 统计行为
        behavior_statistics = self._analyze_behavior_statistics(attention_data_list)
        
        # 评估课堂氛围
        classroom_atmosphere = self._evaluate_classroom_atmosphere(
            average_attention_score, average_participation_score, behavior_statistics
        )
        
        # 分析参与趋势
        engagement_trends = self._analyze_engagement_trends(attention_data_list, participation_data_list)
        
        # 计算学习有效性
        learning_effectiveness = self._calculate_learning_effectiveness(
            average_attention_score, average_participation_score, classroom_atmosphere
        )
        
        # 生成建议
        recommendations = self._generate_classroom_recommendations(
            average_attention_score, average_participation_score, behavior_statistics, classroom_atmosphere
        )
        
        return ClassroomAnalysisResult(
            analysis_id=analysis_id,
            classroom_id=classroom_id,
            session_id=session_id,
            analysis_period=analysis_period,
            student_count=student_count,
            average_attention_score=average_attention_score,
            average_participation_score=average_participation_score,
            attention_distribution=attention_distribution,
            participation_distribution=participation_distribution,
            behavior_statistics=behavior_statistics,
            classroom_atmosphere=classroom_atmosphere,
            engagement_trends=engagement_trends,
            learning_effectiveness=learning_effectiveness,
            recommendations=recommendations
        )
    
    def _analyze_attention_distribution(self, attention_data_list: List[StudentAttentionData]) -> Dict[str, int]:
        """分析专注度分布"""
        distribution = defaultdict(int)
        for data in attention_data_list:
            distribution[data.attention_level.value] += 1
        return dict(distribution)
    
    def _analyze_participation_distribution(self, participation_data_list: List[StudentParticipationData]) -> Dict[str, int]:
        """分析参与度分布"""
        distribution = defaultdict(int)
        for data in participation_data_list:
            distribution[data.participation_level.value] += 1
        return dict(distribution)
    
    def _analyze_behavior_statistics(self, attention_data_list: List[StudentAttentionData]) -> Dict[str, int]:
        """分析行为统计"""
        behavior_stats = defaultdict(int)
        for data in attention_data_list:
            behavior_stats[data.behavior.value] += 1
        return dict(behavior_stats)
    
    def _evaluate_classroom_atmosphere(self, avg_attention: float, avg_participation: float,
                                     behavior_stats: Dict[str, int]) -> ClassroomAtmosphere:
        """评估课堂氛围"""
        # 计算综合分数
        attention_weight = 0.4
        participation_weight = 0.3
        behavior_weight = 0.3
        
        # 行为分数计算
        total_behaviors = sum(behavior_stats.values())
        positive_behaviors = (
            behavior_stats.get('listening', 0) +
            behavior_stats.get('taking_notes', 0) +
            behavior_stats.get('raising_hand', 0) +
            behavior_stats.get('discussing', 0)
        )
        behavior_score = (positive_behaviors / total_behaviors * 100) if total_behaviors > 0 else 0
        
        # 综合评分
        overall_score = (
            avg_attention * attention_weight +
            avg_participation * participation_weight +
            behavior_score * behavior_weight
        )
        
        # 确定氛围等级
        if overall_score >= 85:
            return ClassroomAtmosphere.EXCELLENT
        elif overall_score >= 70:
            return ClassroomAtmosphere.GOOD
        elif overall_score >= 55:
            return ClassroomAtmosphere.AVERAGE
        elif overall_score >= 40:
            return ClassroomAtmosphere.POOR
        else:
            return ClassroomAtmosphere.VERY_POOR
    
    def _analyze_engagement_trends(self, attention_data_list: List[StudentAttentionData],
                                 participation_data_list: List[StudentParticipationData]) -> Dict[str, Any]:
        """分析参与趋势"""
        # 按时间排序
        attention_data_sorted = sorted(attention_data_list, key=lambda x: x.timestamp)
        
        # 计算时间段内的趋势
        if len(attention_data_sorted) < 2:
            return {'trend': 'insufficient_data'}
        
        # 分时段统计（每10分钟一个时段）
        time_segments = defaultdict(list)
        start_time = attention_data_sorted[0].timestamp
        
        for data in attention_data_sorted:
            segment = int((data.timestamp - start_time).total_seconds() // 600)  # 10分钟段
            time_segments[segment].append(data.attention_score)
        
        # 计算各时段平均分数
        segment_averages = []
        for segment in sorted(time_segments.keys()):
            avg_score = np.mean(time_segments[segment])
            segment_averages.append(avg_score)
        
        # 计算趋势
        if len(segment_averages) >= 2:
            x = np.arange(len(segment_averages))
            y = np.array(segment_averages)
            slope = np.polyfit(x, y, 1)[0]
            
            if slope > 2:
                trend = 'improving'
            elif slope < -2:
                trend = 'declining'
            else:
                trend = 'stable'
        else:
            trend = 'stable'
            slope = 0
        
        return {
            'trend': trend,
            'slope': slope,
            'segment_averages': segment_averages,
            'volatility': np.std(segment_averages) if segment_averages else 0
        }
    
    def _calculate_learning_effectiveness(self, avg_attention: float, avg_participation: float,
                                        atmosphere: ClassroomAtmosphere) -> float:
        """计算学习有效性"""
        # 基础有效性分数
        base_score = (avg_attention * 0.5 + avg_participation * 0.5)
        
        # 氛围调整系数
        atmosphere_multipliers = {
            ClassroomAtmosphere.EXCELLENT: 1.1,
            ClassroomAtmosphere.GOOD: 1.0,
            ClassroomAtmosphere.AVERAGE: 0.9,
            ClassroomAtmosphere.POOR: 0.8,
            ClassroomAtmosphere.VERY_POOR: 0.7
        }
        
        multiplier = atmosphere_multipliers.get(atmosphere, 1.0)
        effectiveness = base_score * multiplier
        
        return max(0, min(100, effectiveness))
    
    def _generate_classroom_recommendations(self, avg_attention: float, avg_participation: float,
                                          behavior_stats: Dict[str, int],
                                          atmosphere: ClassroomAtmosphere) -> List[str]:
        """生成课堂建议"""
        recommendations = []
        
        # 专注度建议
        if avg_attention < 60:
            recommendations.append("建议增加互动环节，提高学生专注度")
            recommendations.append("考虑调整教学节奏，避免学生疲劳")
        
        # 参与度建议
        if avg_participation < 50:
            recommendations.append("鼓励学生更多参与课堂讨论")
            recommendations.append("设计更多互动问答环节")
        
        # 行为建议
        distracted_count = behavior_stats.get('distracted', 0)
        sleeping_count = behavior_stats.get('sleeping', 0)
        total_count = sum(behavior_stats.values())
        
        if total_count > 0:
            if distracted_count / total_count > 0.2:
                recommendations.append("注意课堂纪律，减少学生分心行为")
            
            if sleeping_count / total_count > 0.1:
                recommendations.append("调整教室环境，确保学生保持清醒")
        
        # 氛围建议
        if atmosphere in [ClassroomAtmosphere.POOR, ClassroomAtmosphere.VERY_POOR]:
            recommendations.append("整体课堂氛围需要改善，建议调整教学方法")
            recommendations.append("增加师生互动，营造积极的学习氛围")
        
        return recommendations


class LearningPredictor:
    """学习效果预测器"""
    
    def __init__(self):
        self.student_profiles = {}
        self.learning_patterns = defaultdict(list)
        
        # 学习风格权重
        self.learning_style_weights = {
            'visual': {'attention_visual_cues': 0.4, 'note_taking': 0.3, 'reading': 0.3},
            'auditory': {'listening': 0.5, 'discussion': 0.3, 'verbal_participation': 0.2},
            'kinesthetic': {'interaction': 0.4, 'hands_on': 0.3, 'movement': 0.3}
        }
    
    def predict_learning_outcome(self, student_id: str, 
                               attention_history: List[StudentAttentionData],
                               participation_history: List[StudentParticipationData]) -> LearningPrediction:
        """预测学习效果"""
        prediction_id = str(uuid4())
        
        # 分析学习模式
        learning_patterns = self._analyze_learning_patterns(attention_history, participation_history)
        
        # 识别学习风格
        learning_style = self._identify_learning_style(learning_patterns)
        
        # 预测表现
        predicted_performance = self._predict_performance(learning_patterns, learning_style)
        
        # 评估风险等级
        risk_level = self._assess_risk_level(predicted_performance, learning_patterns)
        
        # 识别优势和劣势
        strengths, weaknesses = self._identify_strengths_weaknesses(learning_patterns, learning_style)
        
        # 生成个性化建议
        recommendations = self._generate_personalized_recommendations(
            learning_style, strengths, weaknesses, risk_level
        )
        
        # 计算预测置信度
        confidence = self._calculate_prediction_confidence(attention_history, participation_history)
        
        return LearningPrediction(
            student_id=student_id,
            prediction_id=prediction_id,
            predicted_performance=predicted_performance,
            risk_level=risk_level,
            learning_style=learning_style,
            strengths=strengths,
            weaknesses=weaknesses,
            recommendations=recommendations,
            confidence=confidence
        )
    
    def _analyze_learning_patterns(self, attention_history: List[StudentAttentionData],
                                 participation_history: List[StudentParticipationData]) -> Dict[str, Any]:
        """分析学习模式"""
        if not attention_history:
            return {}
        
        patterns = {}
        
        # 专注度模式
        attention_scores = [data.attention_score for data in attention_history]
        patterns['avg_attention'] = np.mean(attention_scores)
        patterns['attention_stability'] = 100 - np.std(attention_scores)
        patterns['attention_trend'] = self._calculate_trend(attention_scores)
        
        # 参与度模式
        if participation_history:
            participation_scores = [data.participation_score for data in participation_history]
            patterns['avg_participation'] = np.mean(participation_scores)
            patterns['participation_stability'] = 100 - np.std(participation_scores)
            patterns['participation_trend'] = self._calculate_trend(participation_scores)
        else:
            patterns['avg_participation'] = 0
            patterns['participation_stability'] = 0
            patterns['participation_trend'] = 0
        
        # 行为模式
        behavior_counts = defaultdict(int)
        for data in attention_history:
            behavior_counts[data.behavior.value] += 1
        
        total_behaviors = sum(behavior_counts.values())
        patterns['behavior_distribution'] = {
            behavior: count / total_behaviors for behavior, count in behavior_counts.items()
        } if total_behaviors > 0 else {}
        
        # 时间模式（一天中不同时段的表现）
        hourly_performance = defaultdict(list)
        for data in attention_history:
            hour = data.timestamp.hour
            hourly_performance[hour].append(data.attention_score)
        
        patterns['peak_hours'] = []
        patterns['low_hours'] = []
        
        for hour, scores in hourly_performance.items():
            avg_score = np.mean(scores)
            if avg_score > 75:
                patterns['peak_hours'].append(hour)
            elif avg_score < 50:
                patterns['low_hours'].append(hour)
        
        return patterns
    
    def _identify_learning_style(self, patterns: Dict[str, Any]) -> str:
        """识别学习风格"""
        if not patterns:
            return "mixed"
        
        behavior_dist = patterns.get('behavior_distribution', {})
        
        # 视觉学习者特征
        visual_score = (
            behavior_dist.get('reading', 0) * 0.4 +
            behavior_dist.get('taking_notes', 0) * 0.6
        )
        
        # 听觉学习者特征
        auditory_score = (
            behavior_dist.get('listening', 0) * 0.5 +
            behavior_dist.get('discussing', 0) * 0.5
        )
        
        # 动觉学习者特征
        kinesthetic_score = (
            behavior_dist.get('raising_hand', 0) * 0.6 +
            patterns.get('avg_participation', 0) / 100 * 0.4
        )
        
        # 确定主要学习风格
        scores = {
            'visual': visual_score,
            'auditory': auditory_score,
            'kinesthetic': kinesthetic_score
        }
        
        max_style = max(scores.items(), key=lambda x: x[1])
        
        # 如果分数差异不大，则为混合型
        if max_style[1] < 0.3 or (max(scores.values()) - min(scores.values())) < 0.2:
            return "mixed"
        
        return max_style[0]
    
    def _predict_performance(self, patterns: Dict[str, Any], learning_style: str) -> float:
        """预测学习表现"""
        if not patterns:
            return 50.0  # 默认中等表现
        
        # 基础表现分数
        base_score = (
            patterns.get('avg_attention', 50) * 0.4 +
            patterns.get('avg_participation', 50) * 0.3 +
            patterns.get('attention_stability', 50) * 0.2 +
            patterns.get('participation_stability', 50) * 0.1
        )
        
        # 学习风格调整
        style_adjustments = {
            'visual': 0.05 if patterns.get('behavior_distribution', {}).get('reading', 0) > 0.2 else -0.05,
            'auditory': 0.05 if patterns.get('behavior_distribution', {}).get('listening', 0) > 0.3 else -0.05,
            'kinesthetic': 0.05 if patterns.get('avg_participation', 0) > 60 else -0.05,
            'mixed': 0.02  # 混合型学习者适应性较强
        }
        
        adjustment = style_adjustments.get(learning_style, 0)
        adjusted_score = base_score * (1 + adjustment)
        
        # 趋势调整
        attention_trend = patterns.get('attention_trend', 0)
        participation_trend = patterns.get('participation_trend', 0)
        trend_adjustment = (attention_trend + participation_trend) * 0.1
        
        final_score = adjusted_score + trend_adjustment
        
        return max(0, min(100, final_score))
    
    def _assess_risk_level(self, predicted_performance: float, patterns: Dict[str, Any]) -> str:
        """评估风险等级"""
        # 基于预测表现的基础风险
        if predicted_performance >= 75:
            base_risk = "low"
        elif predicted_performance >= 60:
            base_risk = "medium"
        else:
            base_risk = "high"
        
        # 基于稳定性的风险调整
        attention_stability = patterns.get('attention_stability', 50)
        participation_stability = patterns.get('participation_stability', 50)
        
        if attention_stability < 30 or participation_stability < 30:
            # 不稳定的表现增加风险
            if base_risk == "low":
                base_risk = "medium"
            elif base_risk == "medium":
                base_risk = "high"
        
        # 基于负面行为的风险调整
        behavior_dist = patterns.get('behavior_distribution', {})
        negative_behaviors = (
            behavior_dist.get('distracted', 0) +
            behavior_dist.get('sleeping', 0) +
            behavior_dist.get('using_phone', 0)
        )
        
        if negative_behaviors > 0.3:  # 超过30%的负面行为
            if base_risk == "low":
                base_risk = "medium"
            elif base_risk == "medium":
                base_risk = "high"
        
        return base_risk
    
    def _identify_strengths_weaknesses(self, patterns: Dict[str, Any], 
                                     learning_style: str) -> Tuple[List[str], List[str]]:
        """识别优势和劣势"""
        strengths = []
        weaknesses = []
        
        if not patterns:
            return strengths, weaknesses
        
        # 专注度相关
        avg_attention = patterns.get('avg_attention', 50)
        if avg_attention > 75:
            strengths.append("专注度高，能够长时间集中注意力")
        elif avg_attention < 50:
            weaknesses.append("专注度不足，容易分心")
        
        # 参与度相关
        avg_participation = patterns.get('avg_participation', 50)
        if avg_participation > 70:
            strengths.append("课堂参与度高，积极互动")
        elif avg_participation < 40:
            weaknesses.append("课堂参与度低，缺乏主动性")
        
        # 稳定性相关
        attention_stability = patterns.get('attention_stability', 50)
        if attention_stability > 70:
            strengths.append("学习状态稳定，表现一致")
        elif attention_stability < 40:
            weaknesses.append("学习状态不稳定，表现波动较大")
        
        # 行为模式相关
        behavior_dist = patterns.get('behavior_distribution', {})
        
        if behavior_dist.get('taking_notes', 0) > 0.3:
            strengths.append("善于记笔记，学习方法良好")
        
        if behavior_dist.get('raising_hand', 0) > 0.2:
            strengths.append("积极举手发言，勇于表达")
        
        if behavior_dist.get('distracted', 0) > 0.2:
            weaknesses.append("容易分心，需要提高自控能力")
        
        if behavior_dist.get('sleeping', 0) > 0.1:
            weaknesses.append("课堂上容易困倦，需要调整作息")
        
        # 学习风格相关
        if learning_style == "visual":
            strengths.append("视觉学习能力强，适合图表和文字材料")
        elif learning_style == "auditory":
            strengths.append("听觉学习能力强，适合讲解和讨论")
        elif learning_style == "kinesthetic":
            strengths.append("动手学习能力强，适合实践和互动")
        elif learning_style == "mixed":
            strengths.append("学习方式灵活，适应性强")
        
        return strengths, weaknesses
    
    def _generate_personalized_recommendations(self, learning_style: str, strengths: List[str],
                                             weaknesses: List[str], risk_level: str) -> List[str]:
        """生成个性化建议"""
        recommendations = []
        
        # 基于学习风格的建议
        style_recommendations = {
            'visual': [
                "多使用图表、图像和视觉材料辅助学习",
                "制作思维导图和概念图来整理知识",
                "使用颜色标记重点内容"
            ],
            'auditory': [
                "多参与课堂讨论和小组交流",
                "录制学习内容并反复听取",
                "大声朗读和复述重要概念"
            ],
            'kinesthetic': [
                "多参与实践活动和实验",
                "使用手势和动作辅助记忆",
                "定期起身活动，避免长时间静坐"
            ],
            'mixed': [
                "结合多种学习方式，保持学习的多样性",
                "根据内容特点选择最适合的学习方法",
                "保持学习方式的灵活性"
            ]
        }
        
        recommendations.extend(style_recommendations.get(learning_style, []))
        
        # 基于风险等级的建议
        if risk_level == "high":
            recommendations.extend([
                "需要额外的学习支持和指导",
                "建议与老师或同学多交流学习方法",
                "制定详细的学习计划并严格执行"
            ])
        elif risk_level == "medium":
            recommendations.extend([
                "保持当前的学习状态，适当调整学习方法",
                "注意学习效率的提升"
            ])
        
        # 基于劣势的针对性建议
        for weakness in weaknesses:
            if "专注度不足" in weakness:
                recommendations.append("尝试番茄工作法，分段学习提高专注度")
            elif "参与度低" in weakness:
                recommendations.append("主动参与课堂讨论，提高学习参与度")
            elif "不稳定" in weakness:
                recommendations.append("建立规律的学习习惯，保持状态稳定")
            elif "分心" in weakness:
                recommendations.append("创造专注的学习环境，减少干扰因素")
            elif "困倦" in weakness:
                recommendations.append("调整作息时间，确保充足的睡眠")
        
        return list(set(recommendations))  # 去重
    
    def _calculate_trend(self, scores: List[float]) -> float:
        """计算趋势"""
        if len(scores) < 2:
            return 0
        
        x = np.arange(len(scores))
        y = np.array(scores)
        slope = np.polyfit(x, y, 1)[0]
        
        return slope
    
    def _calculate_prediction_confidence(self, attention_history: List[StudentAttentionData],
                                       participation_history: List[StudentParticipationData]) -> float:
        """计算预测置信度"""
        # 基于数据量的置信度
        data_count = len(attention_history) + len(participation_history)
        data_confidence = min(1.0, data_count / 50)  # 50个数据点为满分
        
        # 基于数据质量的置信度
        if attention_history:
            avg_detection_confidence = np.mean([data.confidence for data in attention_history])
        else:
            avg_detection_confidence = 0.5
        
        # 基于数据时间跨度的置信度
        if attention_history:
            time_span = (max(data.timestamp for data in attention_history) - 
                        min(data.timestamp for data in attention_history)).days
            time_confidence = min(1.0, time_span / 30)  # 30天为满分
        else:
            time_confidence = 0.1
        
        # 综合置信度
        overall_confidence = (
            data_confidence * 0.4 +
            avg_detection_confidence * 0.4 +
            time_confidence * 0.2
        )
        
        return max(0.1, min(1.0, overall_confidence))


class ClassroomQualityService:
    """课堂质量评估服务"""
    
    def __init__(self):
        self.attention_detector = AttentionDetector()
        self.participation_analyzer = ParticipationAnalyzer()
        self.classroom_analyzer = ClassroomAnalyzer()
        self.learning_predictor = LearningPredictor()
        
        # 数据存储
        self.attention_data_storage = defaultdict(list)
        self.participation_data_storage = defaultdict(list)
        self.classroom_analysis_storage = {}
        self.learning_predictions_storage = {}
    
    async def analyze_student_attention(self, image: np.ndarray, student_detections: List[Dict[str, Any]]) -> List[StudentAttentionData]:
        """分析学生专注度"""
        attention_data_list = []
        
        for detection in student_detections:
            student_id = detection['student_id']
            bbox = detection['bbox']  # (x, y, w, h)
            
            try:
                attention_data = await self.attention_detector.detect_student_attention(
                    image, bbox, student_id
                )
                attention_data_list.append(attention_data)
                
                # 存储数据
                self.attention_data_storage[student_id].append(attention_data)
                
            except Exception as e:
                logger.error(f"分析学生 {student_id} 专注度失败: {str(e)}")
        
        return attention_data_list
    
    async def analyze_student_participation(self, student_ids: List[str], 
                                          audio_features: Optional[Dict[str, Any]] = None) -> List[StudentParticipationData]:
        """分析学生参与度"""
        participation_data_list = []
        
        for student_id in student_ids:
            # 获取最新的专注度数据
            attention_history = self.attention_data_storage.get(student_id, [])
            if not attention_history:
                continue
            
            latest_attention = attention_history[-1]
            
            try:
                participation_data = await self.participation_analyzer.analyze_student_participation(
                    student_id, latest_attention, audio_features
                )
                participation_data_list.append(participation_data)
                
                # 存储数据
                self.participation_data_storage[student_id].append(participation_data)
                
            except Exception as e:
                logger.error(f"分析学生 {student_id} 参与度失败: {str(e)}")
        
        return participation_data_list
    
    def analyze_classroom_session(self, classroom_id: str, session_id: str,
                                time_range: Optional[Tuple[datetime, datetime]] = None) -> ClassroomAnalysisResult:
        """分析课堂会话"""
        # 收集指定时间范围内的数据
        attention_data_list = []
        participation_data_list = []
        
        for student_id, attention_history in self.attention_data_storage.items():
            for data in attention_history:
                if time_range is None or (time_range[0] <= data.timestamp <= time_range[1]):
                    attention_data_list.append(data)
        
        for student_id, participation_history in self.participation_data_storage.items():
            for data in participation_history:
                if time_range is None or (time_range[0] <= data.timestamp <= time_range[1]):
                    participation_data_list.append(data)
        
        # 执行课堂分析
        analysis_result = self.classroom_analyzer.analyze_classroom_session(
            classroom_id, session_id, attention_data_list, participation_data_list
        )
        
        # 存储分析结果
        self.classroom_analysis_storage[analysis_result.analysis_id] = analysis_result
        
        return analysis_result
    
    def predict_student_learning(self, student_id: str) -> LearningPrediction:
        """预测学生学习效果"""
        attention_history = self.attention_data_storage.get(student_id, [])
        participation_history = self.participation_data_storage.get(student_id, [])
        
        if not attention_history:
            raise ValueError(f"学生 {student_id} 没有足够的历史数据进行预测")
        
        # 执行学习效果预测
        prediction = self.learning_predictor.predict_learning_outcome(
            student_id, attention_history, participation_history
        )
        
        # 存储预测结果
        self.learning_predictions_storage[prediction.prediction_id] = prediction
        
        return prediction
    
    def get_student_attention_summary(self, student_id: str, 
                                    time_range: Optional[Tuple[datetime, datetime]] = None) -> Dict[str, Any]:
        """获取学生专注度摘要"""
        attention_history = self.attention_data_storage.get(student_id, [])
        
        if not attention_history:
            return {'error': f'学生 {student_id} 没有专注度数据'}
        
        # 筛选时间范围内的数据
        if time_range:
            filtered_data = [data for data in attention_history 
                           if time_range[0] <= data.timestamp <= time_range[1]]
        else:
            filtered_data = attention_history
        
        if not filtered_data:
            return {'error': '指定时间范围内没有数据'}
        
        # 计算统计信息
        attention_scores = [data.attention_score for data in filtered_data]
        attention_levels = [data.attention_level.value for data in filtered_data]
        behaviors = [data.behavior.value for data in filtered_data]
        
        # 统计分布
        level_distribution = defaultdict(int)
        behavior_distribution = defaultdict(int)
        
        for level in attention_levels:
            level_distribution[level] += 1
        
        for behavior in behaviors:
            behavior_distribution[behavior] += 1
        
        return {
            'student_id': student_id,
            'data_count': len(filtered_data),
            'time_range': time_range,
            'average_attention_score': np.mean(attention_scores),
            'max_attention_score': max(attention_scores),
            'min_attention_score': min(attention_scores),
            'attention_stability': 100 - np.std(attention_scores),
            'attention_level_distribution': dict(level_distribution),
            'behavior_distribution': dict(behavior_distribution),
            'most_common_level': max(level_distribution.items(), key=lambda x: x[1])[0],
            'most_common_behavior': max(behavior_distribution.items(), key=lambda x: x[1])[0]
        }
    
    def get_classroom_statistics(self, classroom_id: str,
                               time_range: Optional[Tuple[datetime, datetime]] = None) -> Dict[str, Any]:
        """获取课堂统计信息"""
        # 收集所有相关的分析结果
        relevant_analyses = []
        for analysis in self.classroom_analysis_storage.values():
            if analysis.classroom_id == classroom_id:
                if time_range is None or (
                    analysis.analysis_period[0] >= time_range[0] and 
                    analysis.analysis_period[1] <= time_range[1]
                ):
                    relevant_analyses.append(analysis)
        
        if not relevant_analyses:
            return {'error': f'课堂 {classroom_id} 在指定时间范围内没有分析数据'}
        
        # 计算统计信息
        avg_attention_scores = [analysis.average_attention_score for analysis in relevant_analyses]
        avg_participation_scores = [analysis.average_participation_score for analysis in relevant_analyses]
        atmospheres = [analysis.classroom_atmosphere.value for analysis in relevant_analyses]
        learning_effectiveness = [analysis.learning_effectiveness for analysis in relevant_analyses]
        
        # 统计氛围分布
        atmosphere_distribution = defaultdict(int)
        for atmosphere in atmospheres:
            atmosphere_distribution[atmosphere] += 1
        
        return {
            'classroom_id': classroom_id,
            'analysis_count': len(relevant_analyses),
            'time_range': time_range,
            'average_attention_score': np.mean(avg_attention_scores),
            'average_participation_score': np.mean(avg_participation_scores),
            'average_learning_effectiveness': np.mean(learning_effectiveness),
            'attention_score_trend': self._calculate_trend(avg_attention_scores),
            'participation_score_trend': self._calculate_trend(avg_participation_scores),
            'atmosphere_distribution': dict(atmosphere_distribution),
            'most_common_atmosphere': max(atmosphere_distribution.items(), key=lambda x: x[1])[0],
            'total_students_analyzed': sum(analysis.student_count for analysis in relevant_analyses)
        }
    
    def _calculate_trend(self, scores: List[float]) -> str:
        """计算趋势"""
        if len(scores) < 2:
            return 'stable'
        
        x = np.arange(len(scores))
        y = np.array(scores)
        slope = np.polyfit(x, y, 1)[0]
        
        if slope > 1:
            return 'improving'
        elif slope < -1:
            return 'declining'
        else:
            return 'stable'


# 使用示例
if __name__ == "__main__":
    import asyncio
    
    async def main():
        service = ClassroomQualityService()
        
        # 模拟学生检测结果
        student_detections = [
            {'student_id': 'student_001', 'bbox': (100, 100, 80, 120)},
            {'student_id': 'student_002', 'bbox': (200, 100, 80, 120)},
            {'student_id': 'student_003', 'bbox': (300, 100, 80, 120)}
        ]
        
        # 模拟图像数据
        image = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
        
        # 分析学生专注度
        attention_data_list = await service.analyze_student_attention(image, student_detections)
        print(f"分析了 {len(attention_data_list)} 名学生的专注度")
        
        for data in attention_data_list:
            print(f"学生 {data.student_id}: 专注度 {data.attention_score:.1f}, 等级 {data.attention_level.value}")
        
        # 分析学生参与度
        student_ids = [det['student_id'] for det in student_detections]
        participation_data_list = await service.analyze_student_participation(student_ids)
        print(f"\n分析了 {len(participation_data_list)} 名学生的参与度")
        
        for data in participation_data_list:
            print(f"学生 {data.student_id}: 参与度 {data.participation_score:.1f}, 等级 {data.participation_level.value}")
        
        # 分析课堂会话
        classroom_analysis = service.analyze_classroom_session("classroom_001", "session_001")
        print(f"\n课堂分析结果:")
        print(f"平均专注度: {classroom_analysis.average_attention_score:.1f}")
        print(f"平均参与度: {classroom_analysis.average_participation_score:.1f}")
        print(f"课堂氛围: {classroom_analysis.classroom_atmosphere.value}")
        print(f"学习有效性: {classroom_analysis.learning_effectiveness:.1f}")
        
        # 预测学习效果
        for student_id in student_ids:
            try:
                prediction = service.predict_student_learning(student_id)
                print(f"\n学生 {student_id} 学习预测:")
                print(f"预测表现: {prediction.predicted_performance:.1f}")
                print(f"风险等级: {prediction.risk_level}")
                print(f"学习风格: {prediction.learning_style}")
                print(f"建议数量: {len(prediction.recommendations)}")
            except ValueError as e:
                print(f"学生 {student_id}: {str(e)}")
    
    # asyncio.run(main())
    
    async def process_video_frame(self, frame: np.ndarray, metadata: Dict[str, Any] = None) -> Dict[str, Any]:
        """处理视频帧进行课堂质量分析"""
        try:
            camera_id = metadata.get('camera_id', 'unknown') if metadata else 'unknown'
            classroom_id = metadata.get('classroom_id', f'classroom_{camera_id}') if metadata else f'classroom_{camera_id}'
            frame_timestamp = datetime.fromisoformat(metadata.get('frame_timestamp')) if metadata and metadata.get('frame_timestamp') else datetime.now()
            
            # 模拟学生检测结果
            student_detections = self._generate_mock_student_detections(frame)
            
            # 分析学生专注度
            attention_data_list = await self.analyze_student_attention(frame, student_detections)
            
            # 分析学生参与度
            student_ids = [det['student_id'] for det in student_detections]
            participation_data_list = await self.analyze_student_participation(student_ids)
            
            # 分析课堂会话
            session_id = f"session_{int(frame_timestamp.timestamp())}"
            classroom_analysis = self.analyze_classroom_session(classroom_id, session_id)
            
            # 计算整体质量指标
            overall_quality = self._calculate_overall_quality(
                attention_data_list, participation_data_list, classroom_analysis
            )
            
            return {
                "algorithm": "classroom_quality",
                "camera_id": camera_id,
                "frame_timestamp": frame_timestamp.isoformat(),
                "processing_timestamp": datetime.now().isoformat(),
                "results": {
                    "classroom_id": classroom_id,
                    "student_count": len(student_detections),
                    "attention_analysis": {
                        "average_attention_score": np.mean([data.attention_score for data in attention_data_list]) if attention_data_list else 0,
                        "attention_level_distribution": self._get_attention_distribution(attention_data_list),
                        "behavior_distribution": self._get_behavior_distribution(attention_data_list)
                    },
                    "participation_analysis": {
                        "average_participation_score": np.mean([data.participation_score for data in participation_data_list]) if participation_data_list else 0,
                        "participation_level_distribution": self._get_participation_distribution(participation_data_list),
                        "active_students": sum(1 for data in participation_data_list if data.participation_level in [ParticipationLevel.ACTIVE, ParticipationLevel.VERY_ACTIVE])
                    },
                    "classroom_analysis": {
                        "classroom_atmosphere": classroom_analysis.classroom_atmosphere.value,
                        "learning_effectiveness": classroom_analysis.learning_effectiveness,
                        "engagement_score": classroom_analysis.engagement_score,
                        "distraction_level": classroom_analysis.distraction_level
                    },
                    "overall_quality": overall_quality
                },
                "confidence": 0.80,
                "processing_time": 0.3
            }
            
        except Exception as e:
            logger.error(f"课堂质量分析处理视频帧失败: {e}")
            return {
                "algorithm": "classroom_quality",
                "camera_id": metadata.get('camera_id', 'unknown') if metadata else 'unknown',
                "error": str(e),
                "processing_timestamp": datetime.now().isoformat()
            }
    
    def _generate_mock_student_detections(self, frame: np.ndarray) -> List[Dict[str, Any]]:
        """生成模拟学生检测结果"""
        height, width = frame.shape[:2]
        
        # 模拟15-35个学生
        num_students = np.random.randint(15, 36)
        detections = []
        
        for i in range(num_students):
            # 随机生成学生位置（主要在座位区域）
            x = np.random.randint(50, width - 100)
            y = np.random.randint(height//3, height - 100)  # 下方2/3区域
            w = np.random.randint(60, 100)
            h = np.random.randint(80, 120)
            
            detection = {
                'student_id': f'student_{i:03d}',
                'bbox': (x, y, w, h),
                'confidence': np.random.uniform(0.7, 0.95)
            }
            detections.append(detection)
        
        return detections
    
    def _get_attention_distribution(self, attention_data_list: List[StudentAttentionData]) -> Dict[str, int]:
        """获取专注度分布"""
        distribution = defaultdict(int)
        for data in attention_data_list:
            distribution[data.attention_level.value] += 1
        return dict(distribution)
    
    def _get_behavior_distribution(self, attention_data_list: List[StudentAttentionData]) -> Dict[str, int]:
        """获取行为分布"""
        distribution = defaultdict(int)
        for data in attention_data_list:
            distribution[data.behavior.value] += 1
        return dict(distribution)
    
    def _get_participation_distribution(self, participation_data_list: List[StudentParticipationData]) -> Dict[str, int]:
        """获取参与度分布"""
        distribution = defaultdict(int)
        for data in participation_data_list:
            distribution[data.participation_level.value] += 1
        return dict(distribution)
    
    def _calculate_overall_quality(self, attention_data_list: List[StudentAttentionData],
                                 participation_data_list: List[StudentParticipationData],
                                 classroom_analysis: ClassroomAnalysisResult) -> Dict[str, Any]:
        """计算整体质量指标"""
        # 专注度评分 (30%)
        attention_score = np.mean([data.attention_score for data in attention_data_list]) if attention_data_list else 50
        
        # 参与度评分 (30%)
        participation_score = np.mean([data.participation_score for data in participation_data_list]) if participation_data_list else 50
        
        # 课堂氛围评分 (20%)
        atmosphere_scores = {
            ClassroomAtmosphere.VERY_POSITIVE: 95,
            ClassroomAtmosphere.POSITIVE: 85,
            ClassroomAtmosphere.NEUTRAL: 70,
            ClassroomAtmosphere.NEGATIVE: 50,
            ClassroomAtmosphere.VERY_NEGATIVE: 30
        }
        atmosphere_score = atmosphere_scores.get(classroom_analysis.classroom_atmosphere, 70)
        
        # 学习有效性评分 (20%)
        effectiveness_score = classroom_analysis.learning_effectiveness
        
        # 综合评分
        overall_score = (
            attention_score * 0.3 +
            participation_score * 0.3 +
            atmosphere_score * 0.2 +
            effectiveness_score * 0.2
        )
        
        # 确定质量等级
        if overall_score >= 85:
            quality_level = "excellent"
        elif overall_score >= 75:
            quality_level = "good"
        elif overall_score >= 65:
            quality_level = "average"
        elif overall_score >= 50:
            quality_level = "poor"
        else:
            quality_level = "very_poor"
        
        return {
            "overall_score": overall_score,
            "quality_level": quality_level,
            "attention_component": attention_score * 0.3,
            "participation_component": participation_score * 0.3,
            "atmosphere_component": atmosphere_score * 0.2,
            "effectiveness_component": effectiveness_score * 0.2
        }


# 全局课堂质量服务实例
classroom_quality_service = ClassroomQualityService()